/**
 * 日期转换为指定的格式
 */
Date.prototype.format = function(fmt) { 
    var o = { 
       "M+" : this.getMonth()+1,                 //月份 
       "d+" : this.getDate(),                    //日 
       "h+" : this.getHours(),                   //小时 
       "m+" : this.getMinutes(),                 //分 
       "s+" : this.getSeconds(),                 //秒 
       "q+" : Math.floor((this.getMonth()+3)/3), //季度 
       "S"  : this.getMilliseconds()             //毫秒 
   }; 
   if(/(y+)/.test(fmt)) {
           fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
   }
    for(var k in o) {
       if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
   return fmt; 
}


window.msg = {
    'abnormal_network_response': "网络响应异常",
}

// 管理员编辑的成功回调
function adminEditingSuccess(response, newValue) 
{
    if (0 == response.code)
    {
        return response.msg;
    } else if (1 == response.code) {
        if (response.url) {
            window.location.href = response.url;
        }
    }
}
// 管理员编辑的失败回调
function adminEditingError(response, newValue) 
{
    if (response.status = 500)
    {
        return msg.abnormal_network_response;
    } else {
        return response.statusText;
    }
}

// 返回ElementUI的Message选项对象，将使Message弹出错误提示框
function elMessageError(error) 
{
    return {
        message: adminEditingError(error),
        type: 'error',
        showClose: true,
        duration: 0
    };
}

// 返回ElementUI的Message选项
function elMessageOptions(messages='', type="error", duration=0) 
{
    let msg = '';
    if ("string" === typeof messages) {
        msg = messages;
    } else if ( Array.isArray(messages) ) {
        messages.forEach((item, index) => {
            if (0 < index) msg += '<p class="item">' + item + '</p>';
        });
    }
    let options = {
        message: msg,
        type: type,
        dangerouslyUseHTMLString: true,
        showClose: true,
    };
    // 只有成功类型消息会默认3秒后自动消失
    if ("error" === type) options.duration = duration;
    return options;
}

// 返回ElementUI的MessageBox选项
function elMessageBoxOptions(messages='', title='提示', type="warning", beforeClose = null) {
    let msg = '';
    if ("string" === typeof messages) {
        msg = messages;
    } else if ( Array.isArray(messages) ) {
        messages.forEach((item, index) => {
            if (0 < index) msg += '<p class="item">' + item + '</p>';
        });
    }
    let options = {
        title: title,
        message: msg,
        type: type,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        beforeClose: beforeClose
    };
    return options;
}

// 用于bootstrapTable的responseHandler选项来处理响应数据
function responseHandlerBoot(response)
{
    var data = response.data;
    window.roles = [];
    window.icons = [];
    // 提取数据的角色字段供角色列使用
    data.authGroup.forEach(element => {
        roles.push({
            id: element.id, 
            text: element.title
        });
    });
    // 提取数据的头像字段供头像列使用
    data.avatars.forEach(element => {
        for (let key in element) {
            icons.push({
                id: key, 
                text: element[key]
            });
        }
    });
    return data.user;
}

// 用于bootstrapTable的角色字段的行内编辑
function roleEditableBoot(index, row, $element)
{
    // 由于editable的一些选项不起作用，只好手动加属性
    // bootstrap4和bootstrap-editable会有兼容问题
    $element.attr('data-title', '请选择一个角色');
    $element.attr('data-pk', row.id);
    return {
        type: 'select2',
        source: roles,
        // title: '请选择一个角色',
        url: WEB_ADMIN_PATH + CONTROLLER + '/ag_id.html',
        select2: {
            width: 150,
            minimumResultsForSearch: Infinity,
        },
        success: (response, newValue) => {
            return adminEditingSuccess(response, newValue);
        },
        error: (response, newValue) => {
            return adminEditingError(response, newValue, msg.abnormal_network_response);
        }
    }
}

// 用于bootstrapTable的头像字段的行内编辑
function iconEditableBoot(index, row, $element)
{
    // 由于editable的一些选项不起作用，只好手动加属性
    // bootstrap4和bootstrap-editable会有兼容问题
    $element.attr('data-title', '请选择一个头像');
    $element.attr('data-pk', row.id);
    return {
        type: 'select2',
        source: icons,
        url: WEB_ADMIN_PATH + CONTROLLER + '/icon.html',
        select2: {
            width: 200,
            templateSelection: avatars => {
                if (!avatars.id) {
                    return avatars.text;
                }
                let $avatars = $(
                    '<span><img src="' + avatars.element.value + '" class="img-flag" /><span>' +
                    avatars.text + '</span></span>'
                );
                return $avatars;
            },
            templateResult: avatars => {
                if (!avatars.id) {
                    return avatars.text;
                }
                let $avatars = $(
                    '<span><img src="' + avatars.element.value + '" class="img-flag" /> ' + avatars.text + '</span>'
                );
                return $avatars;
            }
        },
        success: (response, newValue) => {
            return adminEditingSuccess(response, newValue);
        },
        error: (response, newValue) => {
            return adminEditingError(response, newValue, msg.abnormal_network_response);
        },
        display: function (value) {
            icons.forEach(ele => {
                if (ele.id == value) {
                    $(this).html(`<img src="${ele.id}">`);
                }
            });
        }
    }
}

// 用于bootstrapTable的昵称字段的行内编辑
function nicknameEditableBoot(index, row, $element)
{
    $element.attr('data-pk', row.id);
    return {
        type: 'text',
        url: WEB_ADMIN_PATH + CONTROLLER + '/admin_nickname.html',
        placeholder: '请输入昵称',
        success: (response, newValue) => {
            return adminEditingSuccess(response, newValue);
        },
        error: (response, newValue) => {
            return adminEditingError(response, newValue, msg.abnormal_network_response);
        }
    }    
}

// 用于bootstrapTable的状态字段的渲染的函数
function statusFormatterBoot(value, row, index, field) 
{
    if (typeof statusData === "undefined") {
        window.statusData = [];
    }
    statusData[index] = value;
    let checked = 'off';
    parseInt(value) && (checked = 'on');
    return `<input id="status-${index}" data-style="status" type="checkbox" data-toggle="switchbutton" data-size="sm" data-onstyle="success" data-offstyle="danger">
            <script>
            $('#table input#status-${index}[data-toggle="switchbutton"]').get(0).switchButton('${checked}')<\/script>`;
}

// 用于bootstrapTable的状态字段的事件处理的函数
function statusEventsBoot(e, value, row, index) 
{
    return {
      "click .status": (e, value, row, index) => {
        axios.put(WEB_ADMIN_PATH + CONTROLLER + '/status?_ajax=1.html', {
            name: "status",
            pk: row.id,
            value: Number(!statusData[index]),
          })
          .then((response) => {
            if (1 == response.data.code)
            {
                let onoff = "on";
                let newValue = parseInt(JSON.parse(response.config.data).value);
                newValue || (onoff = "off");
                statusData[index] = newValue;
                $(e.currentTarget).find('input[type="checkbox"]')[0].switchButton(onoff);
            } else {
                let onoff = "on";
                if (statusData[index] == 0) {
                    onoff = "off";
                }
                $(e.currentTarget)
                  .find('input[type="checkbox"]')[0]
                  .switchButton(onoff);
                throw new Error(response.data.msg);
            }
          })
          .catch((error) => {
            // 模态框方式
            // $('.modal').on('show.bs.modal', function (e) {
            //     let modal = $(this);
            //     modal.find('.modal-title').text('错误！！');
            //     modal.find('.modal-body p').addClass('text-danger').text('{:lang("REQUEST_FAILED", ["' + error.message + '"])}');
            //     modal.find('.modal-footer .footer-save').hide();
            // })
            // $('.modal').modal({
            //     backdrop: 'static',
            // });
            //
            // Toasts弹框方式
            toastr.options = {
              closeButton: true,
              positionClass: "toast-top-center",
              progressBar: true,
              preventDuplicates: true,
            };
            toastr.error(error.message, "请求失败：");
          });
      },
    };
}

// 用于bootstrapTable的最近登录时间字段的渲染的函数
function loginTimeFormatterBoot(value, row, index, field) 
{
    value += '';
    if (10 == value.length) {
        // Date需要13位整数时间戳
        value += '000';
        value = parseInt(value);
    }
    let date = new Date(value).format('yyyy-MM-dd hh:mm:ss');
    return date;
}

// 用于bootstrapTable的邮箱字段的行内编辑
function emailEditableBoot(index, row, $element)
{
    $element.attr('data-pk', row.id);
    return {
        type: "email",
        url: WEB_ADMIN_PATH + CONTROLLER + '/email.html',
        placeholder: '请输入邮箱',
        success: (response, newValue) => {
            return adminEditingSuccess(response, newValue);
        },
        error: (response, newValue) => {
            return adminEditingError(response, newValue, msg.abnormal_network_response);
        },
        validate: function (value) {
            if ($.trim(value) == "") {
                return "这个字段不能为空";
            }
        },
    };
}

// 用于bootstrapTable的操作字段的渲染的函数
function operateFormatterBoot(value, row, index) 
{
    return `<a class="edit mr-2" href="${WEB_ADMIN_PATH}${CONTROLLER}/${row.id}/edit.html" title="编辑">
                <i class="fas fa-edit fa-lg text-info"></i>
            </a>
            <a class="remove" href="javascript:void(0)" title="删除">
                <i class="fa fa-trash fa-lg text-info"></i>
            </a>`;
}

// 用于bootstrapTable的操作字段的事件处理的函数
function operateEventsBoot(e, value, row, index) 
{
    return {
        'click .remove': function (e, value, row, index) {
            Swal.fire({
                title: `你确定要删除ID ${row.id}管理员?`,
                icon: 'question',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showCancelButton: true,
                cancelButtonColor: '#d33',
                showLoaderOnConfirm: true,
                preConfirm: () => {
                    return axios.delete(row.id + '?_ajax=1')
                        .then(response => response)
                        .catch(error => {
                            Swal.showValidationMessage(`请求失败：${error.message}`)
                        })
                }
            }).then((result) => {
                if (result.value) {
                    let response = result.value;
                    let resultData = result.value.data;
                    let timer = null;
                    if (1 === resultData.code) {
                        timer = 1500;
                    } else if (0 === resultData.code) {
                        timer = null;
                    }
                    if (response) {
                        let title = resultData.msg;
                        if (Array.isArray(resultData.msg)) {
                            title = resultData.msg[0];
                        }
                        // 删除成功时
                        if (resultData.code) {
                            Swal.fire({
                                icon: 'success',
                                title: title,
                                width: 350,
                                timer: timer,
                                showConfirmButton: false,
                                allowOutsideClick: false
                            }).then(result => {
                                this.$el.bootstrapTable('removeByUniqueId', row.id)
                            });
                        } else { // 删除失败时
                            Swal.fire({
                                icon: 'error',
                                title: title,
                                html: '',
                                width: 350,
                                timer: timer,
                                confirmButtonColor: '#d33',
                                confirmButtonText: '确定',
                                allowOutsideClick: false,
                                onBeforeOpen: (ele) => {
                                    if (Array.isArray(resultData.msg)) {
                                        const content = Swal.getContent();
                                        if (content) {
                                            let alert = '';
                                            for (const key in resultData.msg) {
                                                if (key > 0 && resultData.msg.hasOwnProperty(key)) {
                                                    const element = resultData.msg[key];
                                                    alert += `<li class="list-group-item list-group-item-danger mb-0">${element}</li>`;
                                                }
                                            }
                                            if (alert) {
                                                content.innerHTML = `<ul class="list-group text-left">${alert}</ul>`;
                                            }
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            })
        }
    };
}

Vue.prototype.goBack = () => history.back(-1);